<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="团队" prop="teamId">
        <el-select v-model="queryParams.teamId" placeholder="请选择团队" clearable>
          <el-option
            v-for="team in teamList"
            :key="team.teamId"
            :label="team.teamName"
            :value="team.teamId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="项目" prop="projectId">
        <el-select v-model="queryParams.projectId" placeholder="请选择项目" clearable>
          <el-option
            v-for="project in projectList"
            :key="project.projectId"
            :label="project.projectName"
            :value="project.projectId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="主要团队" prop="isPrimary">
        <el-select v-model="queryParams.isPrimary" placeholder="请选择" clearable>
          <el-option label="是" :value="true" />
          <el-option label="否" :value="false" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['pm:team:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pm:team:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pm:team:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="Upload"
          @click="handleImport"
          v-hasPermi="['pm:team:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="teamProjectList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="团队名称" align="center" prop="teamName" />
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="是否主要团队" align="center" prop="isPrimary">
        <template #default="scope">
          <el-tag :type="scope.row.isPrimary === true ? 'success' : 'info'">
            {{ scope.row.isPrimary === true ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="View"
            @click="handleView(scope.row)"
            v-hasPermi="['pm:team:query']"
          >查看</el-button>
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pm:team:edit']"
          >修改</el-button>
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pm:team:remove']"
          >删除</el-button>
          <el-button
            link
            type="warning"
            icon="User"
            @click="handleAddMembers(scope.row)"
            v-hasPermi="['pm:team:edit']"
          >添加成员</el-button>
          <el-button
            link
            type="danger"
            icon="Remove"
            @click="handleRemoveMembers(scope.row)"
            v-hasPermi="['pm:team:edit']"
          >移除成员</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改团队项目关联对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="团队" prop="teamId">
          <el-select v-model="form.teamId" placeholder="请选择团队" :disabled="isView">
            <el-option
              v-for="team in teamList"
              :key="team.teamId"
              :label="team.teamName"
              :value="team.teamId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="项目" prop="projectId">
          <el-select v-model="form.projectId" placeholder="请选择项目" :disabled="isView">
            <el-option
              v-for="project in projectList"
              :key="project.projectId"
              :label="project.projectName"
              :value="project.projectId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="主要团队" prop="isPrimary">
          <el-radio-group v-model="form.isPrimary" :disabled="isView">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!isView" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">{{ isView ? '关 闭' : '取 消' }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import type { ElFormInstance } from 'element-plus'
import { listTeamProject, getTeamProject, delTeamProject, addTeamProject, updateTeamProject, associateTeamToProject, disassociateTeamFromProject, addTeamMembersToProject, removeTeamMembersFromProject } from '@/api/pm/team-project'
import { listTeam } from '@/api/pm/team'
import { listProject } from '@/api/pm/project'
import { Search, Refresh, Plus, Edit, Delete, View } from '@element-plus/icons-vue'

// 获取当前实例
const { proxy } = getCurrentInstance() as any

// 表单引用
const formRef = ref<ElFormInstance>()
const queryFormRef = ref<ElFormInstance>()

// 响应式数据
const loading = ref(true)
const ids = ref<number[]>([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const teamProjectList = ref<any[]>([])
const teamList = ref<any[]>([])
const projectList = ref<any[]>([])
const title = ref("")
const open = ref(false)
const isView = ref(false) // 是否为查看模式

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  teamId: null,
  projectId: null,
  isPrimary: null,
})

// 表单参数
const form = ref({
  id: null,
  teamId: null,
  projectId: null,
  isPrimary: false,
})

// 表单校验
const rules = reactive({
  teamId: [
    { required: true, message: "团队不能为空", trigger: "change" }
  ],
  projectId: [
    { required: true, message: "项目不能为空", trigger: "change" }
  ]
})

// 生命周期
onMounted(() => {
  getList()
  getTeamList()
  getProjectList()
})

// 方法定义
/** 查询团队项目关联列表 */
const getList = () => {
  loading.value = true;
  listTeamProject(queryParams).then(response => {
    teamProjectList.value = response.rows || [];
    total.value = response.total || 0;
    loading.value = false;
  }).catch(error => {
    console.error('获取团队项目关联列表失败:', error);
    teamProjectList.value = [];
    total.value = 0;
    loading.value = false;
  });
}

/** 查询团队列表 */
const getTeamList = () => {
  listTeam().then(response => {
    teamList.value = response.rows || [];
  }).catch(error => {
    console.error('获取团队列表失败:', error);
    teamList.value = [];
  });
}

/** 查询项目列表 */
const getProjectList = () => {
  listProject().then(response => {
    projectList.value = response.rows || [];
  }).catch(error => {
    console.error('获取项目列表失败:', error);
    projectList.value = [];
  });
}

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
}

// 表单重置
const reset = () => {
  form.value = {
    id: null,
    teamId: null,
    projectId: null,
    isPrimary: false,
  };
  proxy?.$nextTick(() => {
    formRef.value?.resetFields();
  });
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  proxy?.$nextTick(() => {
    queryFormRef.value?.resetFields();
  });
  handleQuery();
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  open.value = true;
  title.value = "添加团队项目关联";
  isView.value = false;
}

/** 修改按钮操作 */
const handleUpdate = (row?: any) => {
  reset();
  const id = row?.id || ids.value[0]
  getTeamProject(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改团队项目关联";
    isView.value = false;
  });
}

/** 查看按钮操作 */
const handleView = (row: any) => {
  reset();
  const id = row.id
  getTeamProject(id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "查看团队项目关联";
    isView.value = true;
  });
}

/** 提交按钮 */
const submitForm = () => {
  proxy?.$refs["formRef"].validate((valid: boolean) => {
    if (valid) {
      if (form.value.id != null) {
        updateTeamProject(form.value).then(response => {
          proxy?.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addTeamProject(form.value).then(response => {
          proxy?.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
const handleDelete = (row?: any) => {
  const deleteIds = row?.id ? [row.id] : ids.value;
  proxy?.$modal.confirm('是否确认删除团队项目关联编号为"' + deleteIds + '"的数据项？').then(function() {
    return delTeamProject(deleteIds);
  }).then(() => {
    getList();
    proxy?.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 添加团队成员到项目 */
const handleAddMembers = (row: any) => {
  proxy?.$modal.confirm('是否确认将团队"' + row.teamName + '"的所有成员添加到项目"' + row.projectName + '"？').then(function() {
    return addTeamMembersToProject(row.teamId, row.projectId);
  }).then(() => {
    proxy?.$modal.msgSuccess("添加成员成功");
  }).catch(() => {});
}

/** 从项目移除团队成员 */
const handleRemoveMembers = (row: any) => {
  proxy?.$modal.confirm('是否确认从项目"' + row.projectName + '"移除团队"' + row.teamName + '"的所有成员？').then(function() {
    return removeTeamMembersFromProject(row.teamId, row.projectId);
  }).then(() => {
    proxy?.$modal.msgSuccess("移除成员成功");
  }).catch(() => {});
}

/** 导入按钮操作 */
const handleImport = () => {
  proxy?.$modal.msgInfo("导入功能开发中...");
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
</style>
